from api.handler.ce.AbstractBatchCE import AbstractBatchCE
from api.model.BatchOutputPipe import BatchOutputPipe
from api.model.FdInputPipe import FdInputPipe
from munch import Munch
import json
# from config.annotation import Value

class DangerLevelHandler(AbstractBatchCE):
    """ 本科当前状态 包含 当前在校，7内日疫情区 """
    def do_compute(self, output_stream: BatchOutputPipe, source_fds: FdInputPipe, params: dict):
        commu_fd = source_fds.get_fd('Community')
        commu_sql = """
        select CountyName,  count(Level) as Level from
(SELECT distinct Level, CountyName FROM community where DataTime = DATE_SUB(curdate(),INTERVAL 1 DAY)) as a
group by CountyName
        """
        commu_results = commu_fd.query(commu_sql)

        commu_list = []
        for commu in commu_results:
            commu_list.append(commu.CountyName)
        commu_tuple = tuple(commu_list)

        ss_fd = source_fds.get_fd('studentstatus')
        ss_sql = """
        select number, name, sex, dept, grade, major
from studentstatus
        """
        ss_results = ss_fd.query(ss_sql)

        spm_fd = source_fds.get_fd('scupersonmove')
        spm_sql = """
                SELECT DISTINCT PERSONNO
FROM scupersonmove
WHERE DATE > DATE_SUB(curdate(),INTERVAL 7 DAY) AND AREA in {} 
AND (STATUSNAME is null or STATUSNAME='学生')
                """.format(commu_tuple)
        spm_results = spm_fd.query(spm_sql)

        spm1_sql = """
        SELECT PERSONNO, LOCATE
FROM scupersonmove
WHERE DATE = DATE_SUB(curdate(),INTERVAL 1 DAY) AND (STATUSNAME is null or STATUSNAME='学生') AND LOCATE > 0
        """
        spm1_results = spm_fd.query(spm1_sql)

        for ss in ss_results:
            data = Munch()
            data.number = ss.number
            data.name = ss.name
            data.sex = ss.sex
            data.dept = ss.dept
            data.grade = ss.grade
            data.major = ss.major
            data.dangertrip = 0
            data.incollege = 0

            for spm in spm_results:
                if str(ss.number) == str(spm.PERSONNO):
                    data.dangertrip = 1
                    break
            for spm1 in spm1_results:
                if str(ss.number) == str(spm1.PERSONNO):
                    data.incollege = 1
                    break

            output_stream.output_for_upsert(data)



